import { Context, Next } from 'koa'
import { createRandomString, generatorToken } from '../utils/util'
import nodemailer from 'nodemailer'
import redis from '../db/redis'
import GptUser from '../models/gptUser'
import COS from 'cos-nodejs-sdk-v5'
import { TENCENT_COS } from '../config/constant'
import fs from 'fs'
const transporter = nodemailer.createTransport({
  host: 'smtp.qq.com',
  port: 465,
  secure: true,
  auth: {
    user: '927518044@qq.com',
    pass: 'bgauqpdeorrxbfji'
  }
})

const USER_AVATAR =
  'https://bucket-chabaidao-1308160773.cos.ap-guangzhou.myqcloud.com/img/1720878022167/user.webp'

class CommonController {
  // 发送邮件
  async sendEmailCode(ctx: Context, next: Next) {
    const { email } = ctx.request.body
    ctx.verifyParams({
      email: {
        type: 'email'
      }
    })

    const ttl = await redis.ttl(`Verify:${email}`)
    if (ttl > 240) {
      throw `验证码发送太频繁，请稍后再试，【${ttl - 240}】`
    } else {
      const code = createRandomString(6)
      const mailOptions = {
        from: '927518044@qq.com',
        to: email,
        subject: 'gpt邮箱验证',
        text: `您好，你正在进行gpt邮箱验证。\n您的验证码为: ${code}\n验证码 5 分钟内有效，如果不是本人操作，请忽略。`
      }

      redis.setex(`Verify:${email}`, 300, code)
      await transporter.sendMail(mailOptions)
      ctx.body = '验证码已经发送'
    }
    next()
  }
  // 邮件登录
  async emailLogin(ctx: Context, next: Next) {
    const { email, code } = ctx.request.body
    ctx.verifyParams({
      email: {
        type: 'email'
      },
      code: {
        type: 'string',
        min: 6,
        max: 6
      }
    })
    const redisCode = await redis.get(`Verify:${email}`)

    if (redisCode === code) {
      const user = await GptUser.findOne({ email })
      if (user) {
        ctx.body = { token: generatorToken(user._id.toString()) }
      } else {
        const _user = await GptUser.create({ email, name: email, avatar: USER_AVATAR })
        const token = generatorToken(_user._id.toString())
        ctx.body = { token }
      }
      await redis.del(`Verify:${email}`)
    } else {
      throw '验证码错误'
    }
    next()
  }
  // 文件上传
  async upload(ctx: Context, next: Next) {
    const { fileName } = ctx.request.body
    const { file } = ctx.request.files as { file: any }

    if (!file) {
      throw 'file不能为空'
    }
    const { SecretId, SecretKey, Bucket, Region, prefix } = TENCENT_COS
    const cos = new COS({
      SecretId,
      SecretKey
    })

    const Key = prefix + Date.now() + "_" + (fileName || file.originalFilename)
    const res = await cos.putObject({
      Bucket,
      Region,
      Key,
      StorageClass: 'STANDARD',
      Body: fs.readFileSync(file.filepath),
      Headers: { 'Content-Disposition': 'inline', 'Content-Type': file.mime }
    })
    if (res.statusCode === 200) {
      
      if (!ctx.isUpload) {
        ctx.body = { url: `https://${res.Location}`, key: Key, fileType: file.mimetype.split('/')[0] }
        next()
      } else {
        return { url: `https://${res.Location}`, key: Key, fileType: file.mimetype.split('/')[0] }
      }
    } else {
      throw { code: res.statusCode, message: '上传失败' }
    }
  }
}
export default new CommonController()
